/**
 * ----------------------------------------------------------------------------
 * Copyright Jens Konopka
 * 
 * Alle Rechte vorbehalten.
 * Licence: Apache 2.0
 * ----------------------------------------------------------------------------
 *
 * created on 04.03.2012 by jkonopka
 */
package de.sql.toolkit.exporter;

import java.io.File;
import java.util.List;
import java.util.Map;

import de.sql.toolkit.generator.InsertScriptGenerator;
import de.sql.toolkit.reader.InsertScriptReader;
import de.sql.toolkit.util.FilenameUtil;

/**
 * @author jkonopka
 * 
 */
public class InsertScriptExporter extends AbstractExporter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1487626346104281511L;

	/**
	 * @param dstPath
	 * @param schema
	 */
	public InsertScriptExporter(File dstPath, final String schema) {
		super(dstPath, schema);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.sql.toolkit.generator.IGenerator#generate()
	 */
	@Override
	public void export() throws Exception {
		validateDstPath();
		final InsertScriptReader reader = new InsertScriptReader(getSchema());
		final Map<String, List<Map<String, Object>>> values = reader.read();
		for (final Map.Entry<String, List<Map<String, Object>>> entry : values.entrySet()) {
			final Thread thread = new Thread() {

				/*
				 * (non-Javadoc)
				 * 
				 * @see java.lang.Thread#run()
				 */
				@Override
				public void run() {
					try {
						final String key = entry.getKey();
						final List<Map<String, Object>> value = entry.getValue();
						final InsertScriptGenerator writer = new InsertScriptGenerator(key, value);
						final String content = writer.generate();
						final String filename = createFilename("INSERT_TABLE_" + key.toUpperCase());
						writeContentToFile(filename, content);
					} catch (final Exception e) {
						e.printStackTrace();
					}
				}

			};
			thread.start();
		}
	}
	
	/**
	 * @param filename
	 * @return
	 */
	protected String createFilename(final String filename) {
		final StringBuilder sb = new StringBuilder();
		final String path = getDstPath().getAbsolutePath();
		final String concat = FilenameUtil.concat(path, filename);
		sb.append(concat);
		sb.append(".sql");
		return sb.toString();
	}

}
